<template>
  <div class="demand-container">
    <div class="demand-header">
      <h1>需求管理系统</h1>
      <el-button type="primary" @click="openAddDialog">新增需求</el-button>
    </div>

    <div class="demand-search">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="需求标题">
          <el-input v-model="searchForm.title" placeholder="请输入需求标题" clearable />
        </el-form-item>
        <el-form-item label="需求状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable>
            <el-option v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="demand-table">
      <el-table :data="demandList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="需求标题" min-width="200" />
        <el-table-column prop="description" label="需求描述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">{{ getPriorityLabel(scope.row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="demand-pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑需求对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增需求' : '编辑需求'"
      width="50%"
    >
      <el-form :model="demandForm" :rules="demandRules" ref="demandFormRef" label-width="100px">
        <el-form-item label="需求标题" prop="title">
          <el-input v-model="demandForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        <el-form-item label="需求描述" prop="description">
          <el-input v-model="demandForm.description" type="textarea" :rows="4" placeholder="请输入需求描述" />
        </el-form-item>
        <el-form-item label="需求状态" prop="status">
          <el-select v-model="demandForm.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="demandForm.priority" placeholder="请选择优先级">
            <el-option v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDemandList, createDemand, updateDemand, deleteDemand } from '@/api/demand'

// 搜索表单
const searchForm = reactive({
  title: '',
  status: '',
  priority: ''
})

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已拒绝' }
]

// 优先级选项
const priorityOptions = [
  { value: 'low', label: '低' },
  { value: 'medium', label: '中' },
  { value: 'high', label: '高' },
  { value: 'urgent', label: '紧急' }
]

// 需求列表数据
const demandList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const demandFormRef = ref(null)
const demandForm = reactive({
  id: '',
  title: '',
  description: '',
  status: '',
  priority: ''
})

// 表单验证规则
const demandRules = {
  title: [{ required: true, message: '请输入需求标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入需求描述', trigger: 'blur' }],
  status: [{ required: true, message: '请选择需求状态', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
}

// 获取状态标签
const getStatusLabel = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : status
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    processing: 'warning',
    completed: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const option = priorityOptions.find(item => item.value === priority)
  return option ? option.label : priority
}

// 获取优先级标签类型
const getPriorityType = (priority) => {
  const typeMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return typeMap[priority] || 'info'
}

// 搜索
const handleSearch = () => {
  fetchDemandList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.status = ''
  searchForm.priority = ''
  handleSearch()
}

// 获取需求列表
const fetchDemandList = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getDemandList(params)
    demandList.value = res.data.list || []
    pagination.total = res.data.total || 0
  } catch (error) {
    console.error('获取需求列表失败:', error)
    ElMessage.error('获取需求列表失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  Object.keys(demandForm).forEach(key => {
    demandForm[key] = ''
  })
}

// 编辑需求
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 填充表单数据
  Object.keys(demandForm).forEach(key => {
    demandForm[key] = row[key]
  })
}

// 删除需求
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该需求吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDemand(row.id)
      ElMessage.success('删除成功')
      fetchDemandList()
    } catch (error) {
      console.error('删除需求失败:', error)
      ElMessage.error('删除需求失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  demandFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await createDemand(demandForm)
          ElMessage.success('添加成功')
        } else {
          await updateDemand(demandForm.id, demandForm)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchDemandList()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加需求失败:' : '更新需求失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加需求失败' : '更新需求失败')
      }
    }
  })
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchDemandList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchDemandList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchDemandList()
})
</script>

<style scoped>
.demand-container {
  padding: 20px;
}

.demand-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.demand-search {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.demand-table {
  margin-bottom: 20px;
}

.demand-pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
